//
//  MainViewController.swift
//  CopyWB
//
//  Created by imac on 2017/5/12.
//  Copyright © 2017年 iimac. All rights reserved.
//

import UIKit

//主控制器
class MainViewController: UITabBarController {
    //MARK：  - 设置设备旋转支持方向
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupChildControllers()
        setupComposeButton()
        // Do any additional setup after loading the view.
    }
    //MARK: -  监听方法
    //FIXME: 还未实现
    func  composeStatus(){
        print("撰写微博")
        let modalViewController = UIViewController()
        let modalNav = UINavigationController(rootViewController: modalViewController)
        modalViewController.view.backgroundColor = UIColor.cz_random()
        present(modalNav, animated: true, completion: nil)
    }
    
    
    
    //MARK: - 私有控件
    lazy var composeButton : UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName:"tabbar_compose_button")
    
}


extension MainViewController{
    
    func setupComposeButton(){
        tabBar.addSubview(composeButton)
        //设置按钮的位置
        let count = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width / count - 1
        
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        //设置监听方法
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
        
    }
    
    func setupChildControllers(){
        // 0. 获取沙盒 json 路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        // 加载data
        var data = NSData(contentsOfFile: jsonPath)
        
        // 判断 data路径是否有内容，如果没有内容则本地沙盒没有文件 ， 需要加载默认的json
        if data == nil {
            // 从bundle 加载data
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            
            data = NSData(contentsOfFile: path!)
        }
        // data一定会有一个内容 ， 这时候 需要反序列化json 来读取 数据内容
        
        //反序列化转换成数组
        guard  let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String : Any]]
        else{
            return
        }
        
        // 遍历数组,循环创建控制器
        var arrayM = [UIViewController]()
        for dict in array!{
            arrayM.append(controller(dict: dict))
        }
        // 设置 tabbar 的子控制器
        viewControllers = arrayM
    }
    //利用字典创建一个字控制器   dict : [clsName ,title , imageName , visitorInfo]
    private func controller(dict : [String : Any]) -> UIViewController{
        
        guard let clsName = dict["clsName"] as? String,
                let title = dict["title"] as? String,
                let imageName = dict["imageName"] as? String,
                let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? BaseViewController.Type,
                let visitorDict = dict["visitorInfo"] as? [String : String]
            
        else{
                    
                return UIViewController()
        }
        let vc = cls.init()
        
        vc.title = title
        
        // 设置控制器的访客信息字典
        vc.visitorInfoDict = visitorDict
        
        //设置tabbar标题字体
        //设置tabbar颜色
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.orange], for: .highlighted)
        //设置tabbar字体大小 默认为12。修改字体大小需要设置normal状态无法设置高亮状态
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 12)], for: .normal)
        
        
        //MARK : UIViewController 中的 tabBarItem 和 tabBarController
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        let nav = WBNavigationController(rootViewController: vc)
        
        return nav
        
    }
}
